package com.bjfu.demo.controller;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bjfu.demo.dto.ArticleDto;
import com.bjfu.demo.service.ArticleService;
import com.bjfu.demo.utils.Result;
import com.bjfu.demo.valid.AddGroup;
import com.bjfu.demo.valid.UpdateGroup;
import com.github.pagehelper.PageHelper;

/**
 * @create 2021-02-22 10:46
 */
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    //TODO 0.文章的分页查询
    @GetMapping("/getArticleAll/{pageNum}/{pageSize}")
    public Object getAll(@PathVariable("pageNum") Integer pageNum,
                         @PathVariable("pageSize") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        return articleService.selectAll();
    }

    //TODO 1.文章的发布
    @PostMapping("/publishArticle")
    public Result<Integer> publishArticle(@Validated(AddGroup.class) ArticleDto articleDto) {
        int affectRows = articleService.publishArticle(articleDto);
        if (affectRows > 0) {
            return Result.ok("发布成功", affectRows);
        }
        return Result.fail("发布失败");
    }

    //TODO 2.文章的修改
    @PostMapping("/updateArticle")
    public Result<Integer> updateArticle(@Validated(UpdateGroup.class) ArticleDto articleDto) {
        int affectRows = articleService.updateArticle(articleDto);
        if (affectRows > 0) {
            return Result.ok("修改成功", affectRows);
        }
        return Result.fail("修改失败");
    }

    //TODO 3.文章的查询
    @PostMapping("/selectArticle")
    public Result<List<ArticleDto>> selectArticle(ArticleDto articleDto) {
        if (articleDto.getId() == null && articleDto.getTitle() == null) {
            return Result.fail("查询失败，请输入有效的查询条件");
        } else if (articleDto.getId() != null) {
            ArticleDto result = articleService.selectArticle(articleDto.getId());
            return Result.ok("查询成功", Collections.singletonList(result));
        }
        List<ArticleDto> articleDtos = articleService.selectArticle(articleDto);
        return Result.ok("查询成功", articleDtos);
    }


    //TODO 4.文章的删除
    @PostMapping("/deleteArticleByArticleId")
    public Result<Integer> deleteArticleByArticleId(@Validated(UpdateGroup.class) ArticleDto articleDto) {
        int affectRows = articleService.deleteArticleByArticleId(articleDto);
        if (affectRows > 0) {
            return Result.ok("删除成功", affectRows);
        }
        return Result.fail("删除失败");
    }
}
